package com.haust.community.advice;

import com.haust.community.utils.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Auther: csp1999
 * @Date: 2020/11/26/20:39
 * @Description: 异常通知类
 */
// 所有带 @Controller 注解的类都会被扫描到
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    // 声明日志工厂
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 自定义异常处理器,覆盖spring boot原来的异常处理器
     * @param e 异常对象
     * @param request 请求
     * @param response 响应
     * @throws IOException
     */
    @ExceptionHandler({Exception.class})// 标识该方法是用来做异常处理的，处理的异常级别为Exception
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 记录异常信息
        logger.error("请求 URL : {} , 异常信息 : {}",request.getRequestURL(),e);

        // 逐条记录错误日志
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
        } else {
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }
}
